//
//  DTTargetView.m
//  DayToDo
//
//  Created by karry on 2021/1/25.
//

#import "DTTargetView.h"

@interface DTTargetView()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIView *bgView;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIView *snapView;

@property (nonatomic, assign) CGRect sourceRect;

@property (nonatomic, assign) BOOL noDismissDuration;//dismiss时，是否取消延时

@property (nonatomic, assign) BOOL isChat;//是否是聊天
@property (nonatomic, assign) CGFloat keyboardHeight;//chat键盘


@end

@implementation DTTargetView

+ (instancetype)initWithBarItem:(UIBarButtonItem *)barItem
                           item:(NSArray *)items{
    
    UIView *barButtonView = [barItem valueForKey:@"view"];
    DTTargetView *view = [[DTTargetView alloc]initWithTargetView:barButtonView barItem:barItem item:items noDismissDuration:NO isChat:NO keyboardHeight:0];
    return view;
    
}
- (instancetype)initWithTargetView:(UIView *)targetView
                              item:(NSArray *)items
                   noDismissDuration:(BOOL)noDismissDuration {
    return [self initWithTargetView:targetView barItem:nil item:items noDismissDuration:noDismissDuration isChat:NO keyboardHeight:0];
}

- (instancetype)initWithTargetView:(UIView *)targetView
                              item:(NSArray *)items
                            isChat:(BOOL)isChat
                    keyboardHeight:(CGFloat)keyboardHeight{
    return [self initWithTargetView:targetView barItem:nil item:items noDismissDuration:NO isChat:isChat keyboardHeight:keyboardHeight];

}

- (instancetype)initWithTargetView:(UIView *)targetView
                              item:(NSArray *)items
{
    return [self initWithTargetView:targetView barItem:nil item:items noDismissDuration:NO isChat:NO keyboardHeight:0];
}

- (instancetype)initWithTargetView:(UIView *)targetView
                           barItem:(UIBarButtonItem *)barItem
                              item:(NSArray *)items
                   noDismissDuration:(BOOL)noDismissDuration
                            isChat:(BOOL)isChat
                    keyboardHeight:(CGFloat)keyboardHeight{
    
    if (self = [super initWithFrame:UIWindow.keyWindow.frame]) {
        self.frame = [UIScreen mainScreen].bounds;
        _targetView = targetView;
        _barItem = barItem;
        _sourceRect = [targetView.superview convertRect:targetView.frame toView:UIWindow.keyWindow];
        _items = items;
        _noDismissDuration = noDismissDuration;
        _isChat = isChat;
        _keyboardHeight = keyboardHeight;
        [self setupView];
    }
    return self;
}


- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = UIColor.clearColor;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 12, 0, 12);
        _tableView.separatorColor = [UIColor mi_3_color];
        [_tableView registerClass:[DTTargetViewCell class] forCellReuseIdentifier:@"DTTargetViewCellId"];
    }
    return _tableView;
}

- (void)setupView{
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didChangeRotate) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didChangeRotate) name:USNotificationTarget object:nil];

    self.bgView = [UIView new];
    self.bgView.alpha = 0;
    if (self.barItem) {
        self.bgView.backgroundColor = UIColor.clearColor;
    }else{
        self.bgView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:.3];
    }

    @weakify(self)
    [self.bgView jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        @strongify(self)
        [self dissmiss];
    }];
    
    [self addSubview:self.bgView];
    
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_offset(0);
    }];
    
    
    UIView *snapView = nil;
    snapView = [self.targetView snapshotViewAfterScreenUpdates:NO];
    _snapView = snapView;
    
    if (!self.barItem) {
        self.targetView.hidden = YES;
    }
    
    snapView.frame = self.sourceRect;
    if (!self.isChat) {
        snapView.layer.zPosition = MAXFLOAT;
    }
    snapView.userInteractionEnabled = NO;
    snapView.frame = self.sourceRect;

    [self addSubview:snapView];
 
    [self addSubview:self.tableView];
    
    CGFloat midY = CGRectGetMidY(self.sourceRect);
    
    BOOL top = YES;
    
    if (midY > UIWindow.keyWindow.jk_centerY) {
        
        _items = [_items reverseObjectEnumerator].allObjects;
        
        top = NO;
    }else{
        
        top = YES;
    }
    
    CGFloat w = 160;
    
    CGFloat h = 50 * self.items.count;
    
    self.tableView.scrollEnabled = NO;
    self.tableView.alpha = 0;
    
    CGFloat y = self.snapView.jk_bottom;
    
    CGFloat margin = 12;
    
    if (!top) {
        y = self.snapView.jk_top - h - margin;
    }else{
        y = self.snapView.jk_bottom + margin;
    }
     
    BOOL isMiddle = NO;//展示在中间,兼容聊天长按

    if (self.isChat) {
        BOOL fullHeight = self.snapView.jk_height  + h + 60 + 44 + UIWindow.keyWindow.safeAreaInsets.top + UIWindow.keyWindow.safeAreaInsets.bottom> UIWindow.keyWindow.jk_height - self.keyboardHeight;

        BOOL hasNoTopSpace = self.snapView.jk_top < h + 12 + 44 + UIWindow.keyWindow.safeAreaInsets.top;
        BOOL hasNoBottomSpace = self.snapView.jk_bottom > UIWindow.keyWindow.jk_height - self.keyboardHeight - h - 60 - 12 - UIWindow.keyWindow.safeAreaInsets.bottom;

        if (fullHeight && hasNoTopSpace && hasNoBottomSpace) {
            isMiddle = YES;
        }else{
            if (hasNoBottomSpace) {
                y = self.snapView.jk_top - h - margin;
            }
        }
    }
    if (self.targetView.jk_width > w) {
        
        if (top) {
            self.tableView.layer.anchorPoint = CGPointMake(0.5, 0);
        }else{
            self.tableView.layer.anchorPoint = CGPointMake(0.5, 1);
        }
        
        if (isMiddle) {
            self.tableView.layer.anchorPoint = CGPointMake(0.5, 0.5);

            self.tableView.frame = CGRectMake((self.jk_width - w)*.5, self.snapView.jk_bottom/2, w, h);

        }else{
            self.tableView.frame = CGRectMake((self.jk_width - w)*.5, y, w, h);

        }
 
        
    }else{
        
        if (self.sourceRect.origin.x < self.jk_width *0.5) {
            
            if (top) {
                self.tableView.layer.anchorPoint = CGPointZero;
            }else{
                self.tableView.layer.anchorPoint = CGPointMake(0, 1);
            }
       
            self.tableView.frame = CGRectMake(self.snapView.jk_left, y, w, h);
        }else{
            
            if (top) {
                self.tableView.layer.anchorPoint = CGPointMake(1, 0);
            }else{
                self.tableView.layer.anchorPoint = CGPointMake(1, 1);
            }
       
            self.tableView.frame = CGRectMake(self.snapView.jk_right - w, y, w, h);
        }
        
    }

}


- (void)show{
    
    [USFeedbackTool impactMedium];
    
    self.tableView.transform = CGAffineTransformMakeScale(0.1, 0.1);

    [UIView animateWithDuration:0.2 animations:^{
        self.tableView.alpha = 1;
        self.bgView.alpha = 1;
        self.snapView.transform = CGAffineTransformMakeScale(1.05, 1.05);
        self.tableView.transform = CGAffineTransformMakeScale(1, 1);
    }];
    
    
    [UIWindow.keyWindow addSubview:self];
    
}


- (void)didChangeRotate{
    [self dissmiss];
}
- (void)dissmiss{
    
    CGFloat duration = 0.2;
    if (self.noDismissDuration) {
        duration = 0.0;
    }
    [UIView animateWithDuration:duration animations:^{
        self.tableView.alpha = 0;
        self.bgView.alpha = 0;
        self.snapView.transform = CGAffineTransformIdentity;
        self.tableView.transform = CGAffineTransformMakeScale(0.1, 0.1);
    }completion:^(BOOL finished) {
        !self.dissmissBlock?:self.dissmissBlock();
        self.targetView.hidden = NO;
        [self removeFromSuperview];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [USFeedbackTool impactMedium];
    
    DTItem *item = self.items[indexPath.row];
    
    !item.handler?:item.handler(item);
    
    !self.didClickItemBlock?:self.didClickItemBlock(self.items[indexPath.row]);
    
    [self dissmiss];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.items.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DTTargetViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DTTargetViewCellId"];
    
    DTItem *item = self.items[indexPath.row];
    
    cell.d_titleLabel.text = item.title;
    cell.d_imageView.image = item.image;
    
    if ([item.title isEqualToString:@"删除"]) {
        cell.d_titleLabel.textColor = [UIColor jk_colorWithHex:0xF36257];
    }
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
    
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    NSArray *arr = self.items;
   
   if (arr.count == 1) {
       [cell jk_setRoundedCorners:UIRectCornerAllCorners radius:20];
   }else{
       if (indexPath.row == 0) {
           [cell jk_setRoundedCorners:UIRectCornerTopLeft|UIRectCornerTopRight radius:20];
           cell.separatorInset = UIEdgeInsetsMake(0, 12, 0, 12);
       }else if (indexPath.row == arr.count-1){
           [cell jk_setRoundedCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight radius:20];
           cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0);
       }else{
           cell.layer.mask = nil;
           cell.separatorInset = UIEdgeInsetsMake(0, 12, 0, 12);
       }
   }
}


@end

@implementation DTTargetViewCell


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
    
        [self setupView];
        
    }
    return self;
}

- (void)setupView{
    self.contentView.backgroundColor = UIColor.clearColor;
    self.backgroundColor = UIColor.clearColor;
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UIView *c_view = [UIView new];
    c_view.backgroundColor = [UIColor.mainBgColor jk_lightenColor:0.05];
    [self.contentView addSubview:c_view];
    
    [c_view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(0);
        make.bottom.mas_offset(0);
        make.left.right.mas_offset(0);
    }];
    
    self.d_titleLabel = [UILabel new];
    self.d_titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
    [c_view addSubview:self.d_titleLabel];
    
    [self.d_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(12);
        make.centerY.mas_equalTo(self);
        make.right.mas_offset(-40);
    }];
    
    self.d_imageView = [[UIImageView alloc]init];
    [c_view addSubview:self.d_imageView];
    
    [self.d_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-12);
        make.centerY.mas_equalTo(self);
    }];
    
}


@end
